
import EditAble from '@/components/EditAble';
import { Card, Col, Descriptions, Row, Skeleton, Modal, Tag, List, Input, Select, Tabs, message, Form, Space, Collapse, Tooltip } from 'antd';
import { connect, Link, history } from 'umi';
import { ClockCircleOutlined } from '@ant-design/icons'
import styles from './style.less'
import { PROD_STATUS, PRIORUTY_LEVEL, DEMAND_DETAIL_TYPE } from '@/consts/project'
import { ProdStatus } from '@/pages/projects/components/ProjectProduct/ProdPage'
import ArrayUtils from '@/utils/ArrayUtils';
import UserBrief from '@/components/UserBrief';
import { formetDate } from '@/utils/dateUtils'
import { useEffect, useState } from 'react';
import RichText, { RichTextEdit } from '@/components/RichText'
import { DemandStatus } from '@/pages/projects/components/ProjectDemand';
import TextButton from '@/components/TextButton';
import PriorityLevel from '@/pages/projects/components/PriorityLevel';
import ActionDropdown from '@/components/ActionDropdown';
import { pageDemand } from '@/services/project/demand'
import { update, delDemandDetail, addDemandDetail, listDemandDetail, saveDemandDetail } from '@/services/project/prod';
import { listByRelItemId, addRelItem, delRelItem } from '@/services/project/itemRelation'
import ItemRelType from '@/consts/relItemType';
import ProjectComment from '@/pages/projects/components/ProjectComment'
import ProjectItemLog from '@/pages/projects/components/ProjectItemLog'
import { addItemLog, addCustomItemLog } from '@/services/project/itemLog'

const { Panel } = Collapse;
const { TabPane } = Tabs;

const DemandType = ({ type }) => {
    return <Tag color="blue">{DEMAND_DETAIL_TYPE[type].name}</Tag>
}

const DEMAND_REL_PROD = 'DEMAND_REL_PROD'

const Detail = (props) => {

    const {
        data,
        dispatch,
        projectPermission
    } = props

    const [prodData, setProdData] = useState();
    const [demandList, setDemandList] = useState([]);
    const [demandSearchLoading, setDemandSearchLoading] = useState([]);

    const [isDetailTextEditFlag, setIsDetailTextEditFlag] = useState();
    const [relDemandModalVisiable, setRelDemandModalVisiable] = useState();
    const [addDemaneModalVisiable, setAddDemaneModalVisiable] = useState();
    const [relDemandItems, setRelDemandItems] = useState([]);
    const [demandDetailEdit, setDemandDetailEdit] = useState({});
    const [demandDetailList, setDemandDetailList] = useState([])

    const [prodLogUpdate, setProdLogUpdate] = useState(0)
    const [tabKey, setTabKey] = useState()
    const [form] = Form.useForm();
    const [demandParams, setDemandParams] = useState({
        pageSize: 10,
        inStatus: "1,2"
    })
    const [permission, setPermission] = useState({})

    const queryDemandDetail = () => {
        listDemandDetail(data.projectId, data.id).then(({ data }) => {
            setDemandDetailList(data)
        })
    }

    useEffect(() => {
        setProdData(data)
        listByRelItemId(data.projectId, ItemRelType.DEMAND_REL_PROD, data.id).then(({ data }) => {
            setRelDemandItems(data)
        })
        queryDemandDetail();
    }, [data])

    useEffect(() => {
        setPermission({
            ...projectPermission?.prod
        })
    }, [projectPermission])


    if (!prodData) {
        return <Skeleton></Skeleton>
    }


    const updateProd = (values) => {
        update(data.projectId, data.id, values)
            .then(({ success }) => {
                if (success) {
                    message.success("保存成功！")
                }
                if (tabKey === "log") {
                    console.log(prodLogUpdate)
                    setProdLogUpdate(prodLogUpdate + 1)
                }
            })
    }

    const updateName = (name) => {
        updateProd({
            name: name,
            oldData: {
                name: prodData.name
            }
        })
        prodData.name = name;
        setProdData({ ...prodData })
    }

    const updateProjectUser = (userId, user) => {
        updateProd({
            userId: userId,
            payload: {
                userId: user.nickName
            },
            oldData: {
                userId: prodData.userId,
                payload: {
                    userId: prodData.user?.nickName
                }
            }
        })
        prodData.userId = userId;
        prodData.user = user;
        setProdData({ ...prodData })
    }

    const updateStatus = (status) => {
        updateProd({
            status: status,
            oldData: {
                status: prodData.status
            }
        })
        prodData.status = status;
        setProdData({ ...prodData })
    }

    const updateProjectDesc = (description) => {
        updateProd({
            description: description,
            oldData: {
                description: prodData.description
            }
        })
        prodData.description = description;
        setProdData({ ...prodData })
    }

    const updateVersion = (version) => {
        updateProd({
            version: version,
            oldData: {
                version: prodData.version
            }
        })
        prodData.version = version;
        setProdData({ ...prodData })
    }

    const updateActualDate = (actualDate) => {
        updateProd({
            actualStartDate: actualDate[0],
            actualEndDate: actualDate[1],
            oldData: {
                actualStartDate: prodData.actualStartDate,
                actualEndDate: prodData.actualEndDate
            }
        })
        prodData.actualStartDate = actualDate[0];
        prodData.actualEndDate = actualDate[1];
        setProdData({ ...prodData })
    }

    const updateContent = (content) => {
        const oldDataContent = {
            content: {
                text: prodData.content.text
            }
        };
        updateProd({
            content: content,
            oldData: oldDataContent
        })
        prodData.content = content;
        setProdData({ ...prodData })
        setIsDetailTextEditFlag(false)
    }

    const shwoRelDemandModal = () => {
        onSearhDemand()
        setRelDemandModalVisiable(true)
    }
    const addRelDemandItems = (demand) => {
        addRelItem(data.projectId, ItemRelType.DEMAND_REL_PROD, demand.id, data.id)
            .then(({ success }) => {
                if (success) {
                    setRelDemandItems([...relDemandItems, demand])
                    message.success("添加成功")
                    addCustomItemLog(data.projectId, "prod", data.id, [{
                        msg: `添加关联需求`
                    }, {
                        msg: demand.name,
                        payloadType: "DEMAND",
                        payload: {
                            id: demand.id
                        }
                    }]).then(() => {
                        if (tabKey === "log") {
                            setProdLogUpdate(prodLogUpdate + 1)
                        }
                    })
                }
            })
    }

    const delRelDemandItems = (demand) => {
        delRelItem(data.projectId, ItemRelType.DEMAND_REL_PROD, demand.id, data.id)
            .then(({ success }) => {
                if (success) {
                    setRelDemandItems(ArrayUtils.filter(relDemandItems, (item) => item.id !== demand.id))
                    message.success("取消成功");
                    addCustomItemLog(data.projectId, "prod", data.id, [{
                        msg: `删除关联需求`
                    }, {
                        msg: demand.name,
                        payloadType: "DEMAND",
                        payload: {
                            id: demand.id
                        }
                    }]).then(() => {
                        if (tabKey === "log") {
                            setProdLogUpdate(prodLogUpdate + 1)
                        }
                    })
                }
            })
    }

    const relDemandItemsContains = (demandId) => {
        for (const index in relDemandItems) {
            if (relDemandItems[index].id === demandId) {
                return true;
            }
        }
        return false;
    }

    const onSearhDemand = (params) => {
        setDemandSearchLoading(true)
        pageDemand(data.projectId, (params || demandParams)).then(({ data }) => {
            setDemandList(data && data.list)
            setDemandSearchLoading(false)
        })
    }

    const saveProdDemand = async () => {
        const values = await form.validateFields();
        const saveData = {
            ...demandDetailEdit,
            ...values
        }
        if (demandDetailEdit.id) {
            saveDemandDetail(data.projectId, data.id, demandDetailEdit.id, saveData)
                .then(({ success }) => {
                    if (success) {
                        message.success("保存成功！");
                        setDemandDetailEdit({})
                        setAddDemaneModalVisiable(false)
                        queryDemandDetail();
                    }
                    addItemLog(data.projectId, "prod", data.id, `修改需求 ${saveData.name}`).then(() => {
                        if (tabKey === "log") {
                            setProdLogUpdate(prodLogUpdate + 1)
                        }
                    })
                })
        } else {
            addDemandDetail(data.projectId, data.id, saveData)
                .then(({ success }) => {
                    if (success) {
                        message.success("保存成功！");
                        setDemandDetailEdit({})
                        setAddDemaneModalVisiable(false)
                        queryDemandDetail();
                    }
                    addItemLog(data.projectId, "prod", data.id, `新增需求 ${saveData.name}`).then(() => {
                        if (tabKey === "log") {
                            setProdLogUpdate(prodLogUpdate + 1)
                        }
                    })
                })
        }
    }

    const deleteDemandDetail = (item) => {
        delDemandDetail(data.projectId, data.id, item.id)
            .then(({ success }) => {
                if (success) {
                    message.success("删除成功！");
                    queryDemandDetail();
                }
                addItemLog(data.projectId, "prod", data.id, `删除需求 ${item.name}`).then(() => {
                    if (tabKey === "log") {
                        setProdLogUpdate(prodLogUpdate + 1)
                    }
                })
            })
    }
    return <div className={styles.detail}>
        <Row gutter={8}>
            <Col span={16}>
                <Card>
                    <Descriptions column={2}>
                        <Descriptions.Item span={2}>
                            <EditAble permission={permission}
                                value={prodData.name}
                                onSave={updateName}
                                type="input">
                                <h1>{prodData.name}</h1>
                            </EditAble>
                        </Descriptions.Item>
                        <Descriptions.Item label='负责人' span={1}>
                            <EditAble permission={permission}
                                value={prodData.userId}
                                editComponentProps={{
                                    projectId: prodData.projectId,
                                    defaultOpen: true
                                }}
                                onSave={updateProjectUser}
                                type="userSelect">
                                <UserBrief user={prodData.user}></UserBrief>
                            </EditAble>
                        </Descriptions.Item>
                        <Descriptions.Item label='状态' span={1}>
                            <EditAble permission={permission}
                                value={prodData.status}
                                editComponentProps={{
                                    options: ArrayUtils.jsonToArray(PROD_STATUS).map(item => {
                                        return { value: item.key, label: item.value.name }
                                    }),
                                    defaultOpen: true
                                }}
                                onSave={updateStatus}
                                type="select">
                                <ProdStatus status={prodData.status}></ProdStatus>
                            </EditAble>
                        </Descriptions.Item>
                        <Descriptions.Item label="创建时间" span={1}>{prodData.createTime}</Descriptions.Item>
                        <Descriptions.Item label='版本' span={1}>
                            <EditAble permission={permission}
                                value={prodData.version}
                                onSave={updateVersion}
                                type="input">
                                <Tag>{prodData.version}</Tag>
                            </EditAble>
                        </Descriptions.Item>
                        <Descriptions.Item label="排期" span={2}>
                            <EditAble permission={permission}
                                value={[prodData.actualStartDate, prodData.actualEndDate]}
                                editComponentProps={{
                                    format: "YYYY-MM-DD"
                                }}
                                onSave={updateActualDate}
                                type="rangePicker">
                                {`${formetDate(prodData.actualStartDate)} - ${formetDate(prodData.actualEndDate)}`}
                            </EditAble>
                            {prodData.planStartDate && <Tooltip placement="topLeft" title={`预计时间:${formetDate(prodData.planStartDate)} - ${formetDate(prodData.planEndDate)}`}><ClockCircleOutlined /></Tooltip>}
                        </Descriptions.Item>
                        <Descriptions.Item label="概述" span={2} />
                        <Descriptions.Item span={2} >
                            <EditAble permission={permission}
                                editComponentProps={{
                                    rows: 4,
                                    maxLength: 200,
                                    showCount: true
                                }}
                                width='100%'
                                useCustomOperate={true}
                                editComponentClassName={styles.descriptionTextAreaInput}
                                onSave={updateProjectDesc}
                                value={prodData.description}
                                type="textarea">
                                <p>
                                    {prodData.description}
                                </p>
                            </EditAble>
                        </Descriptions.Item>
                    </Descriptions>
                </Card>
                <Card title='需求' extra={
                    <TextButton onClick={() => setAddDemaneModalVisiable(true)}>添加</TextButton>}>
                    <List
                        size="small"
                        itemLayout="vertical"
                        dataSource={demandDetailList}
                        locale={{
                            emptyText: '无内容'
                        }}
                        renderItem={item => (
                            <List.Item>
                                <List.Item.Meta
                                    title={
                                        <div>
                                            <Space>
                                                <PriorityLevel priorityLevel={item.priorityLevel} />
                                                <DemandType type={item.type} />
                                                {item.name}
                                            </Space>
                                            <div style={{ float: "right" }}>
                                                <ActionDropdown
                                                    icon="more"
                                                    actions={[
                                                        <TextButton type="danger" onClick={() => {
                                                            deleteDemandDetail(item)
                                                        }}>删除</TextButton>,
                                                        <TextButton onClick={() => {
                                                            setDemandDetailEdit({
                                                                ...item,
                                                                type: item.type + "",
                                                                priorityLevel: item.priorityLevel + ""
                                                            });
                                                            setAddDemaneModalVisiable(true)
                                                        }}>修改</TextButton>

                                                    ]}
                                                />

                                            </div>
                                        </div>
                                    }
                                />
                                <RichText
                                    collectable
                                    collectConfig={{
                                        collectStyle: "top"
                                    }}
                                    value={item.content.text} />
                            </List.Item>
                        )}
                    />

                </Card>
                <Card title='详细内容'>
                    <EditAble permission={permission}
                        isEdit={isDetailTextEditFlag}
                        onEdit={() => {
                            setIsDetailTextEditFlag(true)
                        }}
                        width="100%"
                        value={prodData.content.raw}
                        onCancel={() => {
                            setIsDetailTextEditFlag(false)
                        }}
                        onSave={() => {
                            setIsDetailTextEditFlag(false)
                        }}
                        useCustomOperate={true}
                        editComponent={
                            <RichTextEdit
                                size="small"
                                onCancel={() => {
                                    setIsDetailTextEditFlag(false)
                                }}
                                onSave={updateContent}
                                value={prodData.content.raw}>
                            </RichTextEdit>
                        }>
                        <RichText
                            value={prodData.content.text}>
                        </RichText>
                    </EditAble>
                </Card>

            </Col>
            <Col span={8} >
                <Card title='关联需求' extra={<TextButton onClick={() => {
                    shwoRelDemandModal();
                }}>添加关联</TextButton>}>
                    <List
                        size="small"
                        locale={{ emptyText: '无关联需求' }}
                        dataSource={relDemandItems}
                        renderItem={item => (
                            <List.Item
                                extra={
                                    <ActionDropdown
                                        icon="more"
                                        actions={[<TextButton type="danger" onClick={() => {
                                            delRelDemandItems(item)
                                        }}
                                        >取消关联</TextButton>]}
                                    />
                                }
                            >
                                <List.Item.Meta
                                    title={<Link to={{
                                        pathname: `/projects/${data.projectId}/demand`,
                                        state: {
                                            demandId: item.id
                                        }
                                    }}>{item.name}</Link>}
                                    description={item.description}
                                />
                            </List.Item>
                        )}
                    />
                </Card>
                <Card style={{ minHeight: "240px" }}>
                    <Tabs
                        defaultValue="comment"
                        activeKey={tabKey}
                        onChange={(tabKey) => {
                            setTabKey(tabKey)
                        }}
                        tabBarGutter={-8}
                        tabBarStyle={{ margin: 0 }}
                    >
                        <TabPane tab="评论" key="comment">
                            <ProjectComment projectId={prodData.projectId} bizId={prodData.id} bizType="prod" />
                        </TabPane>
                        <TabPane tab="日志" key="log">
                            <ProjectItemLog
                                projectId={prodData.projectId}
                                itemId={prodData.id}
                                update={prodLogUpdate}
                                renderField={(value, fieldName) => {
                                    if (fieldName === "status") {
                                        return <ProdStatus status={value}></ProdStatus>
                                    }
                                    if (fieldName === "version") {
                                        return value
                                    }
                                    if (Array.isArray(fieldName) && fieldName.indexOf("actualStartDate") >= 0) {
                                        return `${formetDate(value["actualStartDate"])} - ${formetDate(value["actualEndDate"])}`
                                    }
                                }}
                                renderFieldName={(fieldName) => {
                                    if (fieldName === "version") {
                                        return "版本"
                                    }

                                    if (Array.isArray(fieldName) && (fieldName[0] === "actualStartDate" || fieldName[1] === "actualStartDate")) {
                                        return "排期"
                                    }
                                }}
                                itemType="prod" />
                        </TabPane>
                    </Tabs>
                </Card>
            </Col>
        </Row>

        <Modal title='关联需求'
            width="60%"
            footer={false}
            onCancel={() => setRelDemandModalVisiable(false)}
            visible={relDemandModalVisiable}>
            <List
                header={<Input.Search autoFocus
                    placeholder="请输入名称"
                    loading={demandSearchLoading}
                    onSearch={(name) => {
                        if (name) {
                            onSearhDemand({ likeName: name })
                        } else {
                            onSearhDemand();
                        }
                    }} ></Input.Search>}
                size="small"
                loading={demandSearchLoading}
                dataSource={demandList}
                renderItem={item => <List.Item
                    extra={relDemandItemsContains(item.id) ? <TextButton type="danger" onClick={() => {
                        delRelDemandItems(item)
                    }}
                    >取消</TextButton> :
                        <TextButton onClick={() => {
                            addRelDemandItems(item)
                        }}>关联</TextButton>}
                >
                    <List.Item.Meta
                        title={item.name}
                        description={item.description}
                    />
                    {<DemandStatus status={item.status} />}
                </List.Item>}
            />
        </Modal>
        <Modal title='添加内容'
            okText="确认"
            width="60%"
            destroyOnClose
            cancelText="取消"
            onOk={() => saveProdDemand()}
            onCancel={() => setAddDemaneModalVisiable(false)}
            visible={addDemaneModalVisiable}>
            <Form
                form={form}
                labelAlign="right"
                initialValues={demandDetailEdit}
                labelCol={{ span: 2 }}>
                <Form.Item
                    label={"名称"}
                    name="name"
                    rules={[
                        {
                            required: true,
                            message: "请输入名称",
                        },
                    ]}
                >
                    <Input placeholder={"请输入名称"} maxLength={20} ></Input>
                </Form.Item>
                <Form.Item
                    label={"优先级"}
                    name="priorityLevel"
                    rules={[
                        {
                            required: true,
                            message: "请选择优先级",
                        },
                    ]}
                >
                    <Select placeholder={"请输入优先级"}>
                        {ArrayUtils.jsonToArray(PRIORUTY_LEVEL)
                            .map(item => (<Select.Option key={item.key} value={`${item.key}`}>{item.value.name}</Select.Option>))}
                    </Select>
                </Form.Item>
                <Form.Item
                    label={"类型"}
                    name="type"
                    rules={[
                        {
                            required: true,
                            message: "请选择类型",
                        },
                    ]}
                >
                    <Select placeholder={"请输入类型"}>
                        {ArrayUtils.jsonToArray(DEMAND_DETAIL_TYPE)
                            .map(item => (<Select.Option key={item.key} value={`${item.key}`}>{item.value.name}</Select.Option>))}
                    </Select>
                </Form.Item>
            </Form>
            <RichTextEdit showFormButton={false} value={demandDetailEdit.content && demandDetailEdit.content.raw} size="small" onChange={(content) => {
                setDemandDetailEdit({
                    ...demandDetailEdit,
                    content: content
                })
            }}>
            </RichTextEdit>
        </Modal>
    </div>
}



export default connect(({ }) => ({
}))(Detail);